var a;
var b;
//主表字段缓存
var clons = {};
//明细字段缓存
var itemClons = {};

var tabDiv = "peTabPanel";
//缓存明细对象
var peItemList = new Array();
//缓存查询出的主表对象
var peList = new Array();
//最后点击的记录数
var lastClickRow = -1;

$(function(){
	a = document.documentElement.clientHeight - 110;
 	b = document.documentElement.clientWidth - 20;
    //初始化窗口
 	$('#itemWindow').window({  
	    width:document.documentElement.clientWidth,  
	    height:document.documentElement.clientHeight,  
	    title:'印刷说明明细',
	    resizable:false,
	    maximizable:false,
	    minimizable:false
	}); 
 	$('#itemWindow').window('close');
	$('#parentTabPanel').window('setTitle',"印刷说明单");
	//加载按钮
	loadButns();
	//初始化datagrid
	loadDategrid();
	//加载字段
	loadClns();
	//加载对照信息
	loadDzSource();
});

//加载节点的对照信息
function loadDzSource(){
	$.ajax({
		url:'../../dz/queryDzList',
		type:'post',
		data:{dzIds:'dz_operators;dz_xt;bs_station'},
		success:function(data){
			//xtType 选题类型     author 作者  station 站点 oparator 用户
			oparator = data[0];
			xtList = data[1];
			station = data[2];
		}
	});
}

//查询选题
function queryPrEx(){
	var configStr = parseConfig('QUERYCLN');
	$('#queryConfig').html(parseConfigStr('QUERYCLN'));
	$("#"+tabDiv).tabs('select','印刷说明单列表');
	//加载shuju
	//$('#DATALIST').datagrid({url:'../../framework/loadData?dsId='+datastoreId+"&config="+configStr});
	$.ajax({
		url:'../../framework/loadData',
		data:{dsId:'yz_print_explain',config:configStr},
		success:function(queryJson){
			$('#DATALIST').datagrid("loadData", queryJson);
			peList = queryJson.rows;
			$('#DATALIST').datagrid({url:queryJson.url});
		}
	});
}

//添加印刷说明单
function addPrEx(){
	if(addYWTab(tabDiv,"添加印刷说明单","<div style='padding:20px;'><div id='ADDPAGEBUT'></div><form id='addPEForm'><table id='addPETb'></table></form></div>")!=1){
		makeColumnsWithCol(clons,'addPETb',4);//主表字段
		$.ajax({
			type:'post',
			url:'../../framework/buttonsList',
			data:{'butnId':'yzPrExListS'},
			success:function(data){
				if(data == ""){
					alert("按钮数据为空");
				}else{
					var buttons = data;
					var butHTML = "";
					for(var i = 0; i < buttons.length; i++){
						butHTML += formatButtons(buttons[i]);
					}
					$('#ADDPAGEBUT').html(butHTML);
					$.parser.parse('#ADDPAGEBUT');  //重新编译界面
				}
			}
		});
	}
}


//加载选题字段
function loadClns(){
	$.ajax({
			type:'post',
			url:'../../framework/columnList',
			data:{'colId':'yz_print_explain'},
			success:function(data){
				if(data ==""){
					alert("数据为空");
				}else{
					//请求一个组织列的方法
					clons = data;
					divName='QUERYCLN';//条件字段
					makeQueryColumns(clons,divName);
				}
			}
	});
}

//加载按钮
function loadButns(){
	$.ajax({
		type:'post',
		url:'../../framework/buttonsListC',
		data:{'butnId':"yzPrExList;yzPrExListA"},
		success:function(data){
			if(data == ""){
				alert("按钮数据为空");
			}else{
				var buttons = data;
				var butHTML = "";
				for(var i = 0; i < buttons.length; i++){
					butHTML += formatButtons(buttons[i]);
				}
				$('#BUTTONS').html(butHTML);
				$('#QUERYBUT').html(butHTML);
				$.parser.parse('#BUTTONS');  //重新编译界面
				$.parser.parse('#QUERYBUT');  //重新编译界面
			}
		}
	});
}

//加载数据表格
function loadDategrid(){
	$.ajax({
		type:'post',
		url:'../../framework/listQueryJson',
		data:{'dsId':'yz_print_explain','colId':'yz_print_explain','execFlag':''},
		success:function(data){
			if(data==""){
				alert("数据为空");
			}else{
				//给datagrid赋列值，没有数据
				mdatagrid(data);
			}
		}
	});
}

// 初始化Datagrid
function mdatagrid(data){ //传入的是queryJson 里面就有columns和rows
	var lastIndex;
	$('#DATALIST').datagrid({
		iconCls:'icon-save',
		height:a,
		width:b,
		striped: true,				 
		collapsible:true,
		autoRowHeight: false,		
		sortOrder: 'desc',
		remoteSort: false,
		pageList:[30,50,100,150],
		columns:[[]],
		pagination:true,
		rownumbers:true,
		singleSelect:true,
		onDblClickRow:function(rowIndex,rowData){
			showPEInfo(rowData);
		}
	});
	var dataGridEl = $('#DATALIST');
	dataGridEl.datagrid(jointColumn(data.columns));//根据配置选项，生成datagrid  
}
//点击条件查询
function showQuery(){
	$("#"+tabDiv).tabs('select',"条件查询");
	$('#queryCB').removeAttr('checked');
}

//翻译方法
function operators(value){
	for(var i=0; i<oparator.length; i++){
		if (oparator[i].ID == value) return oparator[i].NAME;
	}
	return value;
}

function xtformater(value){
	for(var i=0; i<xtList.length; i++){
		if (xtList[i].ID == value) return xtList[i].NAME;
	}
	return value;
}
function stationFormater(value){
	for(var i=0; i<station.length; i++){
		if (station[i].ID == value) return station[i].NAME;
	}
	return value;
}

function departFormater(value){
	return "部门未设置"+value;
}


//添加印刷说明单明细
function addPEItem(){
	if(addYWTab(tabDiv,"印刷说明明细","<div style='padding:20px;'><div id='ADDITEMPAGEBUT'></div></div><div><div id='peItemDatagrid'></div></div>")!=1){
		//添加按钮
		$.ajax({
			type:'post',
			url:'../../framework/buttonsListC',
			data:{'butnId':'yzPrExListItemS'},
			success:function(data){
				if(data == ""){
					alert("按钮数据为空");
				}else{
					var buttons = data;
					var butHTML = "";
					for(var i = 0; i < buttons.length; i++){
						butHTML += formatButtons(buttons[i]);
					}
					$('#ADDITEMPAGEBUT').html(butHTML);
					$.parser.parse('#ADDITEMPAGEBUT');  //重新编译界面
				}
			}
		});
		//添加datagrid
		loadItemDategrid();
	}
}

//加载明细数据表格
function loadItemDategrid(){
	if(itemClons.length > 0){
		mItemdatagrid(itemClons);
	}else{
		$.ajax({
			type:'post',
			url:'../../framework/listQueryJson',
			data:{'dsId':'yz_print_explain_item','colId':'yz_print_explain_item','execFlag':''},
			success:function(data){
				if(data==""){
					alert("数据为空");
				}else{
					//给datagrid赋列值，没有数据
					itemClons = data;
					mItemdatagrid(data);
				}
			}
		});
	}
}

//初始化明细Datagrid
function mItemdatagrid(data){ //传入的是queryJson 里面就有columns和rows
	var lastIndex;
	$('#peItemDatagrid').datagrid({
		iconCls:'icon-save',
		height:a-20,
		width:b,
		striped: true,				 
		collapsible:true,
		autoRowHeight: false,		
		sortOrder: 'desc',
		remoteSort: false,
		pageList:[30,50,100,150],
		columns:[[]],
		pagination:true,
		rownumbers:true,
		singleSelect:true,
		onDblClickRow:function(rowIndex,rowData){
			editItemInfo(rowIndex);
		}
	});
	var dataGridEl = $('#peItemDatagrid');
	dataGridEl.datagrid(jointColumn(data.columns));//根据配置选项，生成datagrid  
}

//添加单个明细
function addPEItemSingle(){
	peItemList[peItemList.length] = {
			PE_ID:'',
			PE_ITEM_ID:'',
			GONGYI_PROJECT:'',
			GONGYI_EXPLAIN:'',
			GONGYI_YAOQIU:'',
			GONGYI_ITEM:'',
			ZHANKAI_CHICUN:'',
			CL_ID:'',
			AMOUNT:'',
			PRICE:'',
			UNIT:'',
			CL_MAN:'',
			MEMO:''};
	//添加一条空行
	$('#peItemDatagrid').datagrid('appendRow',peItemList[peItemList.length-1]);
}

//双击之后编辑每条明细
function editItemInfo(rowIndex){
	lastClickRow = rowIndex;
	formatCss();
	if($('#itemCln').html() == ''){
		//加载明细字段
		$.ajax({
			type:'post',
			url:'../../framework/columnList',
			data:{'colId':'yz_print_explain_item'},
			success:function(data){
				if(data ==""){
					alert("数据为空");
				}else{
					divName='itemCln';//条件字段
					makeColumns(data,divName);
					//填充对照信息
					var dzIdstr = serializeEDIType(divName);
					$.ajax({
						url:'../../dz/queryDzList',
						type:'post',
						data:{dzIds:dzIdstr},
						success:function(data){
								//下拉框
								fillSelect(divName,data);
								//填充记录详情
								fillInfo(divName,peItemList[lastClickRow]);
						}
					});
					
				}
			}
		});	
		//添加按钮
		$.ajax({
			type:'post',
			url:'../../framework/buttonsListC',
			data:{'butnId':'yzPrExListItemA'},
			success:function(data){
				if(data == ""){
					alert("按钮数据为空");
				}else{
					var buttons = data;
					var butHTML = "";
					for(var i = 0; i < buttons.length; i++){
						butHTML += formatButtons(buttons[i]);
					}
					$('#itemBut').html(butHTML);
					$.parser.parse('#itemBut');  //重新编译界面
				}
			}
		});
	}else{
		//填充记录详情
		fillInfo('itemCln',peItemList[lastClickRow]);
	}
	//弹出窗口
	$('#itemWindow').window('open');
}
//确定明细的修改
function sureItemInfo(){
	//判断是否有选中的记录  
	var selRow = $('#peItemDatagrid').datagrid('getSelected');
	if(selRow == null)return;
	//缓存中修改ItemList对象信息
	peItemList[lastClickRow] = {
			PE_ID:$('#itemCln input[coluname=PE_ID]').val(),
			PE_ITEM_ID:$('#itemCln input[coluname=PE_ITEM_ID]').val(),
			GONGYI_PROJECT:$('#itemCln select[coluname=GONGYI_PROJECT]').val(),
			GONGYI_EXPLAIN:$('#itemCln textarea[coluname=GONGYI_EXPLAIN]').val(),
			GONGYI_YAOQIU:$('#itemCln textarea[coluname=GONGYI_YAOQIU]').val(),
			GONGYI_ITEM:$('#itemCln input[coluname=GONGYI_ITEM]').val(),
			ZHANKAI_CHICUN:$('#itemCln input[coluname=ZHANKAI_CHICUN]').val(),
			CL_ID:$('#itemCln select[coluname=CL_ID]').val(),
			AMOUNT:$('#itemCln input[coluname=AMOUNT]').val(),
			PRICE:$('#itemCln input[coluname=PRICE]').val(),
			UNIT:$('#itemCln input[coluname=UNIT]').val(),
			CL_MAN:$('#itemCln select[coluname=CL_MAN]').val(),
			MEMO:$('#itemCln input[coluname=MEMO]').val()};
	//刷新datagrid
	selRow.PE_ID=peItemList[lastClickRow].PE_ID;
	selRow.PE_ITEM_ID=peItemList[lastClickRow].PE_ITEM;
	selRow.GONGYI_PROJECT=peItemList[lastClickRow].GONGYI_PROJECT;
	selRow.GONGYI_EXPLAIN=peItemList[lastClickRow].GONGYI_EXPLAIN;
	selRow.GONGYI_YAOQIU=peItemList[lastClickRow].GONGYI_YAOQIU;
	selRow.GONGYI_ITEM=peItemList[lastClickRow].GONGYI_ITEM;
	selRow.ZHANKAI_CHICUN=peItemList[lastClickRow].ZHANGKAI_CHICUN;
	selRow.CL_ID=peItemList[lastClickRow].CL_ID;
	selRow.AMOUNT=peItemList[lastClickRow].AMOUNT;
	selRow.PRICE=peItemList[lastClickRow].PRICE;
	selRow.UNIT=peItemList[lastClickRow].UNIT;
	selRow.CL_MAN=peItemList[lastClickRow].CL_MAN;
	selRow.MEMO=peItemList[lastClickRow].MEMO;
	$('#peItemDatagrid').datagrid('refreshRow', lastClickRow);
}

//上一条或者下一条
function nextOprev(numStr){
	if(numStr=='1' && lastClickRow-- > 0 ){
		fillInfo(divName,peItemList[lastClickRow]);
	}else if(numStr=='2' && lastClickRow++ < peItemList.length-1){
		fillInfo(divName,peItemList[lastClickRow]);
	}else{
		return;
	}
	$('#peItemDatagrid').datagrid('clearSelections');
	$('#peItemDatagrid').datagrid('selectRow',lastClickRow)
	formatCss();
}

//修改界面字体样式
function formatCss(){
	if(lastClickRow == peItemList.length-1){
		$('#pr').css('color','gray');
	}else{
		$('#pr').css('color','black');
	}
	if(lastClickRow == 0){
		$('#ne').css('color','gray');
	}else{
		$('#ne').css('color','black');
	}
	var amoNum = lastClickRow;
	$('#num').html(++amoNum+"/"+peItemList.length);
}

//保存印刷说明单主明细
function savePE(){
	//判断是否有主表信息
	//判断是否有明细记录(如果有空行则提示，是否将空行删除)
	//有则将主表信息和明细的信息传入服务器
	if(!$("#"+tabDiv).tabs('exists','印刷说明明细')){
		$.messager.alert('提示','请添加印刷说明明细','info');
		return;
	}
	if(!$("#"+tabDiv).tabs('exists','添加印刷说明单')){
		$.messager.alert('提示','请重新添加印刷说明单','info');
		return;
	}
	if(delEmptyRow('save')==1){
		//alert('保存');
		
	}else{
		return;	
	}
}

function delEmptyRow(flag){
	//判断空行信息
	var tmp = "";
	var rowsData = $('#peItemDatagrid').datagrid('getRows');
	var rowsLength = rowsData.length;
	var printExplainItemList = {};
	for(var i = 1; i <= rowsLength; i++){
		if(rowsData[i-1].GONGYI_EXPLAIN == '' && rowsData[i-1].GONGYI_YAOQIU == '' ){
			tmp += i+","
		}
	}
	if(tmp != ''){
		//是否删除不符合记录的行
		$.messager.confirm('提示','第'+tmp+'行数据不全，是否删除?', function(btn2){
			//点击确定则保存,否则取消
			if (btn2) {
				for(var i = 0; i < rowsLength; i++){
					if(rowsData[i].GONGYI_EXPLAIN == '' && rowsData[i].GONGYI_YAOQIU == '' ){
						//将缓存和datagrid中的行都删除
						$('#peItemDatagrid').datagrid('deleteRow',i);
						i--;
						rowsLength -= 1;
					}
				}
				peItemList = $('#peItemDatagrid').datagrid('getRows');
				if(flag == 'save'){//继续保存按钮    如果没有，则说明只是删除空白数据
					$.messager.confirm('提示','是否继续保存?', function(btn3){
						//点击确定则保存,否则取消
						if (btn3) {
							printExplainItemList = formatToJsonPro(peItemList)
							//测试保存方法
							ajaxSavePE(printExplainItemList,'addPEForm');
						}
					});
				}
			}
		});
		return 2;
	}else{
		if(flag == 'save'){//继续保存按钮    如果没有，则说明只是删除空白数据
			printExplainItemList = formatToJsonPro(rowsData);
			ajaxSavePE(printExplainItemList,'addPEForm');
		}
		return 1;
	}
}
//印刷说明单明细
function formatToJsonPro(rowsData){
	var kk = new Array();
	for(var k = 0; k < rowsData.length; k++){
		kk[k] = {
				peId:rowsData[k].PE_ID,
			    peItemId:rowsData[k].PE_ITEM_ID,
			    gongyiProject:rowsData[k].GONGYI_PROJECT,
			    gongyiExplain:rowsData[k].GONGYI_EXPLAIN,
			    gongyiYaoqiu:rowsData[k].GONGYI_YAOQIU,
			    gongyiItem:rowsData[k].GONGYI_ITEM,
			    zhankaiChicun:rowsData[k].ZHANKAI_CHICUN,
			    clId:rowsData[k].CL_ID,
			    amount:rowsData[k].AMOUNT,
			    price:rowsData[k].PRICE,
			    unit:rowsData[k].UNIT,
			    clMan:rowsData[k].CL_MAN,
			    memo:rowsData[k].MEMO	
		};
	}
	return kk;
}

//保存印刷说明单
function ajaxSavePE(itemList,formId){
	$.ajax({
		url:"../../printExplain/savePEWI",
		type:'post',
		contentType: "application/json;charset=utf-8",
		data:JSON.stringify(itemList)+"&inputMan=dddd",
		dataType: "json",
		success:function(data){
			alert(data.info);
		}
	});
}

//双击查看详情
function showPEInfo(rowData){
	//显示主表信息
	var contentHTML = "<div style='padding:20px;'><div id='PEINFOPAGEBUT'></div><table id='upPETAB'></table></div><div id='itemListDataG'></div>";
	divName='upPETAB';//条件字段
	if(addYWTab(tabDiv,"印刷说明单详情",contentHTML)!=1){
		//加载字段\按钮
		makeColumnsWithCol(clons,divName,4);
		//加载对照信息
		//因为上述没有ajax 请求，所以可以直接找到每个录入框
		//动态加载对照值   动态填充   全部变灰 //为确保动态对照加载完毕，所以ajax请求不可用封装的方法
		var dzIdstr = serializeEDIType(divName);
		$.ajax({
			url:'../../dz/queryDzList',
			type:'post',
			data:{dzIds:dzIdstr},
			success:function(data){
					//下拉框
					fillSelect(divName,data);
					fillInfo(divName,rowData);
					//将字段变灰
					readOnlyAll(divName);
			}
		});
		//加载多种按钮
		$.ajax({
			type:'post',
			url:'../../framework/buttonsListC',
			data:{'butnId':'yzPrExInfo'},
			success:function(data){
				if(data == ""){
					alert("按钮数据为空");
				}else{
					var buttons = data;
					var butHTML = "";
					for(var i = 0; i < buttons.length; i++){
						butHTML += formatButtons(buttons[i]);
					}
					$('#PEINFOPAGEBUT').html(butHTML);
					$.parser.parse('#PEINFOPAGEBUT');  //重新编译按钮
				}
			}
		});
		//填充info页面的Datagrid
		if(itemClons.length > 0){
			mInfoItemdatagrid(itemClons);
		}else{
			$.ajax({
				type:'post',
				url:'../../framework/listQueryJson',
				data:{'dsId':'yz_print_explain_item','colId':'yz_print_explain_item','execFlag':''},
				success:function(data){
					if(data==""){
						alert("数据为空");
					}else{
						//给datagrid赋列值，没有数据
						itemClons = data;
						mInfoItemdatagrid(data);
					}
				}
			});
		}
	}else{
		fillInfo(divName,rowData);
		//将字段变灰
		readOnlyAll(divName);
	}
	//查询明细记录
	var peId = rowData.PE_ID;
}


//初始化详情页面明细Datagrid
function mInfoItemdatagrid(data){ //传入的是queryJson 里面就有columns和rows
	$('#itemListDataG').datagrid({
		iconCls:'icon-save',
		striped: true,				 
		collapsible:true,
		autoRowHeight: false,		
		sortOrder: 'desc',
		remoteSort: false,
		pageList:[30,50,100,150],
		columns:[[]],
		pagination:true,
		rownumbers:true,
		singleSelect:true,
		onDblClickRow:function(rowIndex,rowData){
		}
	});
	var dataGridEl = $('#itemListDataG');
	dataGridEl.datagrid(jointColumn(data.columns));//根据配置选项，生成datagrid  
}


//------------------------------------------------------------------------------------------------------------------------------
		//选题ID
		var xtid;
		//基础按钮ID
		var butnId = 'XTButton';
		//窗口命名
		var winName = "选题立项";
		//对照信息
		//xtType 选题类型     author 作者  station 站点 oparator 用户
		
		//选中的暂存对象
		var rowObj = {};
		
		
 		
 		//保存选题
		function saveXT(){
			$.ajax({
				type:'post',
				url:'../../bjTopic/saveTopic',
				data:$('#addXTForm').serialize(),
				success:function(data){
					if(data.msg == "success"){
						$('#addXTForm input[name=xtId]').val(data.info);
						$.messager.alert("提示","保存成功");
						//更新按钮
						$.ajax({
							type:'post',
							url:'../../framework/buttonsListC',
							data:{'butnId':'XTaddSave;XTsaveS'},
							success:function(data){
								if(data == ""){
									alert("按钮数据为空");
								}else{
									var buttons = data;
									var butHTML = "";
									for(var i = 0; i < buttons.length; i++){
										butHTML += formatButtons(buttons[i]);
									}
									$('#ADDPAGEBUT').html(butHTML);
									$.parser.parse('#ADDPAGEBUT');  //重新编译按钮
								}
							}
						});
					}else if(data.msg == "upsuccess"){
						$.messager.alert("提示","更新成功");
					}else if(data.msg == "fail"){
					 	$.messager.alert("提示","保存失败！","info");
					}else{
						$.messager.alert("提示",data.msg,"error");
					}
				}
			});
		}
		
		//显示更新界面   1.加载字段  2.填充
		function showUpTab(){
			divName='upTopicTb';//条件字段
			if(addYWTab('xtTabPanel',"修改选题","<div style='padding:20px;'><div id='UPTOPICBUT'></div><form id='upTopicForm'><table id='upTopicTb'></table></form></div>")!=1){
				//加载字段\按钮
				makeColumns(clons,divName);
				$.ajax({
					type:'post',
					url:'../../framework/buttonsListC',
					data:{'butnId':'XTupSave;XTsaveS'}, //XTupSave;XTsaveS 
					success:function(data){
						if(data == ""){
							alert("按钮数据为空");
						}else{
							var buttons = data;
							var butHTML = "";
							for(var i = 0; i < buttons.length; i++){
								butHTML += formatButtons(buttons[i]);
							}
							$('#UPTOPICBUT').html(butHTML);
							$.parser.parse('#UPTOPICBUT');  //重新编译界面
						}
					}
				});
				//加载对照信息
				var dzIdstr = serializeEDIType("upTopicTb");
				$.ajax({
					url:'../../dz/queryDzList',
					type:'post',
					data:{dzIds:dzIdstr},
					success:function(data){
							//下拉框
							fillSelect(divName,data);
							fillInfo(divName,rowObj);
							//将部分字段变灰
							readOnlyPart(divName);
					}
				});
			}else{
				//填充记录
				fillInfo(divName,rowObj);
				readOnlyPart(divName);
			}
		}
		
		//更新选题   只在详情页面有
		function updateXT(){
			$.ajax({
				type:'post',
				url:'../../bjTopic/saveTopic',
				data:$('#upTopicForm').serialize(),
				success:function(data){
					if(data.msg == "success"){
						$('#upTopicForm input[name=xtId]').val(data.info);
						$.messager.alert("提示","保存成功");
					}else if(data.msg == "upsuccess"){
						$.messager.alert("提示","更新成功");
					}else if(data.msg == "fail"){
					 	$.messager.alert("提示","保存失败！","info");
					}else{
						$.messager.alert("提示",data.msg,"error");
					}
				},
				error:function(data,msg,obj){$.messager.alert("提示",obj,"error");}
			});
		}
		
		
		//编辑选题计划
 		function showPlan(){
 			var selXTid = $('#upXTForm input[name=xtId]').val();
 			if(selXTid ==  null || selXTid == '') return;
 			//divName='upTopicPlanTb';//条件字段
			if(addYWTab('xtTabPanel',"编辑选题计划","<div><div id='EtPlanDataGrid'></div></div>")!=1){
				//将EtPlanDataGrid 加载  页面   /node/editFlowManager
				$('#EtPlanDataGrid').load(
					'../../node/editFlowManager',
					{xtId:selXTid},
					function(){
					});
			}else{
				
			}
 		} 